<template>
  <div>
    <div class="box-shadow pad10 mgb10" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="80px"
        class="fnmb"
      >
        <div class="flex jbetween">
          <div>
            <el-form-item label="角色编号" prop="Code">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入权限字符"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="角色名称" prop="Name">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入角色名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
          <div class="flex acenter fnw jend">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <MyTable
      :tableList="roleList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="showSearch"
      v-model:selectList="selectList"
      @switch="rowSwitchChange"
      :btnList="$checkBtn(['Role:edit', 'Role:delete'])"
      @getList="getList"
      @edit="handleUpdate"
      @delete="handleDelete"
    >
      <template v-slot:tabTop>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['Role:add']"
              v-if="props.ShowAdd"
              plain
              icon="CirclePlusFilled"
              @click="handleAdd"
              >添加</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            >
          </el-col> -->
        </el-row>
      </template>
    </MyTable>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      draggable
    >
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="Info.Name">
          <el-input v-model="form.Info.Name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="Info.Code">
          <template #label>
            <span>
              <!-- <el-tooltip
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip> -->
              角色编号
            </span>
          </template>
          <el-input v-model="form.Info.Code" placeholder="请输入角色编号" />
        </el-form-item>
        <!-- <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            controls-position="right"
            :min="0"
          />
        </el-form-item> -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.Info.Enable">
            <el-radio label="Y">启用</el-radio>
            <el-radio label="N">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuRef"
            :check-strictly="!form.menuCheckStrictly"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="{ label: 'ownName', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <!-- <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog
      :title="title"
      v-model="openDataScope"
      width="500px"
      append-to-body
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.Name" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.Code" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == 2">
          <el-checkbox
            v-model="deptExpand"
            @change="handleCheckedTreeExpand($event, 'dept')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="deptNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'dept')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="form.deptCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'dept')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="deptRef"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import {
  listRole,
  getRoleDetail,
  AddRole,
  EditRole,
  DelRole,
  UserBindRole
} from '@/api/system/role';
import { getAllMenus } from '@/api/system/menu.js';
import { onMounted } from 'vue';
import usePermissionStore, {
  formatMenu,
  menusWithButton
} from '@/store/modules/permission.js';
const props = defineProps({
  ShowAdd: { default: true },
  checkList: {
    default: []
  },
  RoleColumns: {
    default: []
  }
});

const emit = defineEmits(['update:checkList']);
const router = useRouter();
const { proxy } = getCurrentInstance();
const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const Total = ref(0);
const title = ref('');
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);

const columns = ref([
  { key: 0, label: '序号', visible: true },
  { key: 1, label: '角色编号', visible: true, prop: 'Code' },
  { key: 2, label: '角色名称', visible: true, prop: 'Name' },
  {
    key: 3,
    label: '状态',
    visible: true,
    tag: true,
    prop: 'tags'
  },
  { key: 4, label: '创建时间', visible: true, prop: 'CreateTime' },
  { key: 5, label: '创建人', visible: true, prop: 'CreateUser', user: true },
  { key: 6, label: '最后更新时间', visible: true, prop: 'UpdateTime' },
  { key: 7, label: '操作', visible: true, width: 190 }
]);
if (props.RoleColumns?.length) {
  columns.value = props.RoleColumns;
  showSearch.value = false;
  proxy.$formatKey(columns.value);
}
/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' }
]);

const data = reactive({
  form: {},
  page: {
    PageIndex: 1,
    PageSize: 10
  },
  queryParams: {
    Name: undefined,
    Code: undefined
    // status: undefined,
  },
  rules: {
    'Info.Name': [
      { required: true, message: '角色名称不能为空', trigger: 'blur' }
    ],
    'Info.Code': [
      { required: true, message: '角色编号不能为空', trigger: 'blur' }
    ],
    roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules, page } = toRefs(data);

onMounted(() => {
  getList();
  initMenus();
});

const selectList = computed({
  get: () => {
    return props.checkList;
  },
  set: v => {
    console.log(v);
    emit('update:checkList', v);
  }
});

async function rowSwitchChange({ row, status }) {
  reset();
  try {
    let res = await getRoleDetail({ ID: row.ID });
    form.value.Info = res.data.Info;
    form.value.Info.Enable = status;
    form.value.Info.ID = row.ID;
    form.value.BindMenus = res.data.Menus?.map(item => {
      return { ID_Menu: item.ID_Menu };
    });
    form.value.BindButtons = res.data.Buttons?.map(item => {
      return { ID_Button: item.ID_Button };
    });
    if (form.value.Info.ID != undefined) {
      await EditRole(form.value);
      proxy.$modal.msgSuccess('修改成功');
      getList();
    } else {
      await AddRole(form.value);
      proxy.$modal.msgSuccess('新增成功');
      getList();
    }
  } catch (error) {
    getList();
    console.log(error);
    return false;
  }
}
async function initMenus() {
  try {
    let allMenus = await getAllMenus({ Code: '', Name: '' });
    let list = formatMenu(allMenus.data);
    let listWithBtn = menusWithButton(list, usePermissionStore().allBtns);
    menuOptions.value = listWithBtn;
  } catch (error) {
    console.log(error);
  }
}
/** 查询角色列表 */
async function getList() {
  try {
    let query = { ...queryParams.value, ...page.value };
    let res = await listRole(query);
    res.data.List?.forEach(item => {
      item.tags = [
        {
          name: item.Enable == 'Y' ? '启用' : '停用',
          type: item.Enable == 'Y' ? 'success' : 'danger'
        }
      ];
    });
    roleList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm('queryRef');
  handleQuery();
}
/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    await DelRole({ ID: row.ID });
    getList();
    proxy.$modal.msgSuccess('删除成功');
  } catch (error) {
    console.log(error);
  }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/role/export',
    {
      ...queryParams.value
    },
    `role_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用';
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.Name + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功');
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0';
    });
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case 'handleDataScope':
      handleDataScope(row);
      break;
    case 'handleAuthUser':
      handleAuthUser(row);
      break;
    default:
      break;
  }
}
/** 分配用户 */
function handleAuthUser(row) {
  router.push('/system/role-auth/user/' + row.roleId);
}
/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    menuOptions.value = response.data;
  });
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys();
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    menuCheckStrictly: false,
    Info: {
      ID: undefined,
      Name: undefined,
      Code: undefined,
      Enable: 'Y'
    },
    // roleSort: 0,
    BindButtons: [],
    BindMenus: []
  };
  proxy.resetForm('roleRef');
}
/** 添加角色 */
async function handleAdd() {
  reset();
  // getMenuTreeselect();
  open.value = true;
  title.value = '添加角色';
}
/** 修改角色 */
async function handleUpdate(row) {
  reset();
  console.log(row);
  try {
    let res = await getRoleDetail({ ID: row.ID });

    open.value = true;
    form.value.Info = res.data.Info;
    form.value.Info.ID = row.ID;
    form.value.BindMenus = res.data.Menus?.map(item => {
      return { ID_Menu: item.ID_Menu };
    });
    form.value.BindButtons = res.data.Buttons?.map(item => {
      return { ID_Button: item.ID_Button };
    });

    nextTick(() => {
      let arr = [];
      form.value.BindMenus?.map(item => {
        // if (
        //   !menuRef.value.getNode(item.ID_Menu).childNodes ||
        //   !menuRef.value.getNode(item.ID_Menu).childNodes.length
        // ) {
        arr.push(item.ID_Menu);
        // }
      });
      form.value.BindButtons?.map(item => {
        // if (
        //   !menuRef.value.getNode(item.ID_Button).childNodes ||
        //   !menuRef.value.getNode(item.ID_Button).childNodes.length
        // ) {
        arr.push(item.ID_Button);
        // }
      });
      menuRef.value.setCheckedKeys(arr);
    });
    title.value = '修改角色';
  } catch (error) {
    console.log(error);
  }
}
/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then(response => {
    menuOptions.value = response.menus;
    return response;
  });
}
/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then(response => {
    deptOptions.value = response.depts;
    return response;
  });
}
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == 'menu') {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == 'dept') {
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == 'menu') {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else if (type == 'dept') {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == 'menu') {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == 'dept') {
    form.value.deptCheckStrictly = value ? true : false;
  }
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedNodes();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedNodes();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['roleRef'].validate(async valid => {
    if (valid) {
      let checkedIds = getMenuAllCheckedKeys();
      form.value.BindButtons = [];
      form.value.BindMenus = [];
      checkedIds?.map(item => {
        if (item.menuType == 'F') {
          form.value.BindButtons.push({ ID_Button: item.id });
        } else {
          form.value.BindMenus.push({ ID_Menu: item.id });
        }
      });

      // console.log(form.value);

      if (form.value.Info.ID != undefined) {
        try {
          await EditRole(form.value);
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        } catch (error) {
          console.log(error);
        }
      } else {
        try {
          await AddRole(form.value);
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        } catch (error) {
          console.log(error);
        }
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== '2') {
    deptRef.value.setCheckedKeys([]);
  }
}
/** 分配数据权限操作 */
function handleDataScope(row) {
  reset();
  const deptTreeSelect = getDeptTree(row.roleId);
  getRole(row.roleId).then(response => {
    form.value = response.data;
    openDataScope.value = true;
    nextTick(() => {
      deptTreeSelect.then(res => {
        nextTick(() => {
          if (deptRef.value) {
            deptRef.value.setCheckedKeys(res.checkedKeys);
          }
        });
      });
    });
    title.value = '分配数据权限';
  });
}
/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then(response => {
      proxy.$modal.msgSuccess('修改成功');
      openDataScope.value = false;
      getList();
    });
  }
}
/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}
</script>
